package com.zw.pm.aspectj;

import com.zw.pm.annotation.LogAnnotation;
import com.zw.pm.gen.entity.Log;
import com.zw.pm.gen.entity.User;
import com.zw.pm.module.system.log.LogService;
import com.zw.pm.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description:  日志切面
 *
 * @Author: China.sgl
 * @Date: 2019/11/28 13:48
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private LogService logService;

    @Pointcut("@annotation(com.zw.pm.annotation.LogAnnotation)")
    private void pointCut() { }

    @After("pointCut()")
    public void recordLog(JoinPoint joinPoint) {
        User user = ShiroUtils.getUser();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        Log log = new Log();
        log.setAccount(user.getAccount());
        log.setName(user.getName());
        log.setOperationName(logAnnotation.value());
        log.setOperationTime(new Date());
        log.setAddress(ShiroUtils.getIp());
        logService.saveLog(log);
    }
}
